/**
 * 
 */
package com.fashop.enabler.container;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.fashop.enabler.bean.container.AccessResponse;
import com.fashop.enabler.bean.container.AuthTenant;
import com.fashop.enabler.bean.container.PasswordCredentials;
import com.fashop.enabler.bean.container.RequestAuthTenant;
import com.fashop.enabler.bean.container.ResponseAccessFinal;
import com.fashop.enabler.bean.container.Tenant;
import com.fashop.enabler.bean.container.Tenants;
import com.fashop.enumeration.HeaderApplicationEnum;
import com.fashop.enumeration.ValueHeaderApplicationEnum;
import com.google.gson.Gson;

/**
 * @author Alan Dávila
 * e-mail ustargab@gmail.com
 * date 26/01/2014 20:33:16
 */
@Service("containerEnablerImpl")
public class ContainerEnablerImpl implements ContainerEnabler {

	private final static Logger LOGGER = Logger.getLogger(ContainerEnablerImpl.class);
	/* (non-Javadoc)
	 * @see com.fashop.enabler.container.ContainerEnabler#getResource(java.lang.String)
	 */
	public String getResource(final Map<String, String> credenciales, final String path) {
		final String repositorio = "http://130.206.82.9:8080";
		HttpResponse httpResponse = null;
		DefaultHttpClient peticion = new DefaultHttpClient();
		String stringEscape = "{}";
		String imagen64 = "";
		try {			
			String auth = credenciales.get("auth");
			String token = credenciales.get("token");
			if (auth != null && "".compareTo(auth) != 0 && token != null && "".compareTo(token) != 0) {
				String url = repositorio + "/cdmi/" + auth + "/" + path;
				HttpGet httpGet = new HttpGet(url);
				httpGet.addHeader(HeaderApplicationEnum.XAUTHTOKEN.getValue(), token);
				httpResponse = peticion.execute(httpGet);
				stringEscape = EntityUtils.toString(httpResponse.getEntity());
				String target = "\\\"";
				String replacement = "";
				stringEscape = stringEscape.replace(target, replacement);
				stringEscape = stringEscape.substring(1);
				stringEscape = stringEscape.substring(0, stringEscape.length() - 1);
				Integer posicionInicial = stringEscape.indexOf("value:") + "value:".length();
				imagen64 = stringEscape.substring(posicionInicial, stringEscape.length() - 1);
			} else {
				imagen64 = "";
			}
		} catch (Exception e) {
			LOGGER.error(e.getClass().toString() + ": No se ha podido ejecutar alguna petición");
		}
		
		return imagen64;
	}
	/* (non-Javadoc)
	 * @see com.fashop.enabler.container.ContainerEnabler#getCredentials(java.lang.String)
	 */
	public Map<String, String> getCredentials(final String proyecto) {
		
		final Map<String, String> credencialesMap = new HashMap<String, String>();
		String tenantEncontrado = "";
		String tokenEncontrado = "";
		
		final String hostAutenticacion = "http://cloud.lab.fi-ware.eu:4730";
		
		final String userName = "1joel1@gmail.com";
		final String password = "miguel";
		String url = hostAutenticacion + "/v2.0/tokens";
		JSONObject objetoRespuesta = null;
		JSONObject inputBody = new JSONObject(); 
		StringEntity entidad = null;
		final Gson gson = new Gson();
		HttpPost httPost;
		HttpGet httpGet;
		
		//token inicial
		AccessResponse accessResponse = null;		
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
		DefaultHttpClient peticion = new DefaultHttpClient(httpParams);
		JSONObject auth = new JSONObject();
		JSONObject passwordCredentials = new JSONObject();
		passwordCredentials.put("username", userName);
		passwordCredentials.put("password", password);
		auth.put("passwordCredentials", passwordCredentials);
		inputBody.put("auth", auth);
		//HttpGet httpGet = new HttpGet(url);
		httPost = new HttpPost(url);
		httPost.addHeader(HeaderApplicationEnum.CONTENT_TYPE.getValue(), ValueHeaderApplicationEnum.APPLICATION.getValue() + "/" + ValueHeaderApplicationEnum.JSON.getValue());
		HttpResponse httpResponse;
		try {
			entidad = new StringEntity(inputBody.toString());
			httPost.setEntity(entidad);
			httpResponse = peticion.execute(httPost);
			objetoRespuesta = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
			accessResponse = gson.fromJson(objetoRespuesta.toString(), AccessResponse.class);

			//get tenant
			Tenants tenantsResponse = null;
			url = hostAutenticacion + "/v2.0/tenants";
			httpGet = new HttpGet(url);		
			httpResponse = null;
			objetoRespuesta = null;
			httpGet.addHeader(HeaderApplicationEnum.XAUTHTOKEN.getValue(), accessResponse.getAccess().getToken().getId());
			httpResponse = peticion.execute(httpGet);
			objetoRespuesta = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
			tenantsResponse = gson.fromJson(objetoRespuesta.toString(), Tenants.class);

			//busco el proyecto
			for(Tenant tenant : tenantsResponse.getTenants()) {
				if (proyecto.compareTo(tenant.getName()) == 0) {
					tenantEncontrado = tenant.getId();
					break;
				}
			}

			//token basado en el tenant
			RequestAuthTenant requestBodyTenant = new RequestAuthTenant();
			ResponseAccessFinal responseAccessFinal = null;
			AuthTenant authTenant = new AuthTenant();
			PasswordCredentials passwordCredentialsRequest = new PasswordCredentials();
			passwordCredentialsRequest.setUsername(userName);
			passwordCredentialsRequest.setPassword(password);		
			authTenant.setPasswordCredentials(passwordCredentialsRequest);;
			authTenant.setTenantName(tenantEncontrado);
			requestBodyTenant.setAuth(authTenant);
			url = hostAutenticacion + "/v2.0/tokens";
			httPost = new HttpPost(url);
			httPost.addHeader(HeaderApplicationEnum.CONTENT_TYPE.getValue(), ValueHeaderApplicationEnum.APPLICATION.getValue() + "/" + ValueHeaderApplicationEnum.JSON.getValue());
			entidad = new StringEntity(gson.toJson(requestBodyTenant, RequestAuthTenant.class));
			httPost.setEntity(entidad);
			httpResponse = peticion.execute(httPost);
			objetoRespuesta = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
			responseAccessFinal = gson.fromJson(objetoRespuesta.toString(), ResponseAccessFinal.class);
			tokenEncontrado = responseAccessFinal.getAccess().getToken().getId();
			tenantEncontrado = "AUTH_" + responseAccessFinal.getAccess().getToken().getTenant().getId();
			
		} catch (Exception e) {
			LOGGER.error(e.getClass().toString() + ": No se ha podido ejecutar alguna petición");
			tokenEncontrado = "";
			tenantEncontrado = "";
		}
		credencialesMap.put("token", tokenEncontrado);
		credencialesMap.put("auth", tenantEncontrado);
		return credencialesMap;
	}

}
